import { ref } from "vue";
import { defineStore } from "pinia";

export const useCarStore = defineStore(
  "carStore",
  () => {
    const car = ref([]);
    const setCar = (value) => {
      // 判断购物车内是否已经存在该商品
      const index = car.value.findIndex((item) => item.id === value.id);
      if (index === -1) {
        // 不存在则直接添加到购物车
        car.value.push(value);
        return;
      }
      // 存在则数量+1
      const newCar = [...car.value];
      newCar[index].count++;
      car.value = newCar;
    };
    const removeCar = (value) => {
      car.value = car.value.filter((item) => {
        return !value.includes(item.id);
      });
    };
    return { car, setCar, removeCar };
  },
  {
    persist: true,
  }
);
